﻿using HCQ2_Common.Constant;
using HCQ2_Model;
using HCQ2_Model.DocModel.APIModel;
using HCQ2_Model.ViewModel.WebAPI;
using HCQ2WebAPI_Logic.BaseAPIController;
using HCQ2WebAPI_Logic.Model;
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Http;
using HCQ2_Model.ViewModel;

namespace HCQ2WebAPI_Logic.DocumentController
{
    /// <summary>
    ///  用户授权API接口
    /// </summary>
    public class DocEmpowerAPIController: BaseWeiXinApiLogic
    {
        #region 1.0  添加授权 + async Task<WebApiResultJsonModel> AddEmpower(EmpowerAPIModel model)
        /// <summary>
        ///  添加授权
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel AddEmpower(EmpowerAPIModel model)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            T_User user = operateContext.bllSession.T_User.Select(s => s.user_guid.Equals(model.userid)).FirstOrDefault();
            //1.0 判断是否允许添加
            if (user.max_machine > 0)
            {
                //统计当前用户下，正常状态 并且 日期在有效期内的数量
                int machNum = operateContext.bllSession.T_DocEmpower.SelectCount(s => s.user_id == user.user_id && s.status == 1 && DateTime.Now >= s.start_date && DateTime.Now <= s.end_date);
                if(machNum>= user.max_machine)
                    return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "已达到绑定机器码最大条数："+ machNum.ToString()+"条，不能再添加了！", null);
            }
            //1.1 添加
            T_DocEmpower power = new T_DocEmpower
            {
                num_code = model.num_code,
                user_id = user.user_id,
                limit_code = "VRPPT_ACCESS",
                status = 0,
                machine_code = model.machine_code,
                machine_name = model.machine_name,
                doc_note = model.doc_note
            };
            int mark = operateContext.bllSession.T_DocEmpower.Add(power);
            if (mark > 0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "添加成功~", null);
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Error, "添加失败~：", null);
        }
        #endregion

        #region 1.1  添加/更改绑定机器 + async Task<WebApiResultJsonModel> ModifyEmpower(ModifyEmpowerModel model)
        /// <summary>
        ///  添加授权
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel ModifyEmpower(ModifyEmpowerModel model)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            T_User user = operateContext.bllSession.T_User.Select(s => s.user_guid.Equals(model.userid)).FirstOrDefault();
            T_DocEmpower power = operateContext.bllSession.T_DocEmpower.Select(s => s.id == model.id).FirstOrDefault();
            if(power==null || !power.status.Equals(1))
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "需要更改绑定的记录不存或未生效~", null);
            if (string.IsNullOrEmpty(power.machine_code))
            {
                #region 未绑定过，添加绑定
                power.machine_code = model.machine_code;
                power.machine_name = model.machine_name;
                power.doc_note = model.doc_note;
                int mark = operateContext.bllSession.T_DocEmpower.Modify(power, s => s.id.Equals(model.id), "machine_code", "machine_name", "doc_note");
                if (mark > 0)
                    return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "绑定成功~", null);
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Error, "绑定失败~：", null);
                #endregion
            }
            else
            {
                #region 更改绑定
                power.end_date = DateTime.Now.AddDays(3);
                //1.1 修改原来记录结束时间为当前时间后的3天
                operateContext.bllSession.T_DocEmpower.Modify(power, s => s.id == power.id, "end_date");
                //1.2 创建新的记录
                T_DocEmpower p = new T_DocEmpower
                {
                    num_code = power.num_code,
                    user_id = power.user_id,
                    limit_code = "VRPPT_ACCESS",
                    status = 0,
                    start_date = DateTime.Now.AddDays(3),
                    end_date = power.end_date,
                    machine_code = power.machine_code,
                    machine_name = power.machine_name,
                    doc_note = model.doc_note,
                    reg_id = power.reg_id,
                    reg_name = power.reg_name,
                    update_id = power.update_id,
                    update_name = power.update_name
                };
                int mark = operateContext.bllSession.T_DocEmpower.Add(p);
                if (mark > 0)
                    return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "更改成功~", null);
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Error, "更改失败~：", null);
                #endregion
            }            
        }
        #endregion

        #region 1.2  解除绑定 + async Task<WebApiResultJsonModel> RelieveEmpower(RelieveEmpowerModel model)
        /// <summary>
        ///  解除绑定
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel RelieveEmpower(RelieveEmpowerModel model)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            T_User user = operateContext.bllSession.T_User.Select(s => s.user_guid.Equals(model.userid)).FirstOrDefault();
            //1.0 找出原来记录
            T_DocEmpower power = operateContext.bllSession.T_DocEmpower.Select(s => s.user_id == user.user_id && s.machine_code.Equals(model.machine_code) && s.status == 1).FirstOrDefault();
            if (power == null)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "需要解除绑定的记录未生效或者不存在！", null);
            power.machine_code = "";
            //1.1 修改原来记录结束时间为当前时间后的3天
            int mark = operateContext.bllSession.T_DocEmpower.Modify(power, s => s.id == power.id, "machine_code");
            if (mark > 0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "解除绑定成功~", null);
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Error, "解除绑定失败~：", null);
        }
        #endregion

        #region 1.3  删除授权 + async Task<WebApiResultJsonModel> DeleteEmpower(RelieveEmpowerModel model)
        /// <summary>
        ///  删除授权
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel DeleteEmpower(DeleteEmpowerModel model)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            int mark = operateContext.bllSession.T_DocEmpower.Delete(s => s.id == model.id);
            if (mark > 0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "删除成功~", null);
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Error, "删除失败~", null);
        }
        #endregion

        #region 1.4  获取授权列表 + async Task<WebApiResultJsonModel> GetSourceFile(DocListParam model)
        /// <summary>
        ///  获取文档列表
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel GetEmPowerData(EmpowerAPPParam model)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            TableModel result = operateContext.bllSession.T_DocEmpower.GetPowerAPPList(model, HCQ2UI_Helper.Session.SysPermissSession.ChangeIdByGuid(model.userid));
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "获取授权列表成功~", result);
        }
        #endregion
    }
}
